//
//  OrdersViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/17.
//

import UIKit
import RxSwift
import RxCocoa
class OrdersViewController: UIViewController {

    struct OrderStateModel {
        let title: String
        let id: Int
        var selected: Bool
    }
    
    private var _status = 4
    
    var status: Int {
        get {
            return _status
        }
        set {
            _status = newValue
            let source = [OrderStateModel(title: "All".locale, id: 4, selected: 4 == newValue),OrderStateModel(title: "Apply".locale, id: 7, selected: 7 == newValue),OrderStateModel(title: "Repayment".locale, id: 6, selected: 6 == newValue),OrderStateModel(title: "Finished".locale, id: 5, selected: 5 == newValue)]
            self.titles.accept(source)
        }
    }
    
    private let bag = DisposeBag()
    
    private let titles = BehaviorRelay<[OrderStateModel]>.init(value: [])
    
    private let currentIndex = PublishSubject<Int>()
    
    private lazy var childs: [UIViewController] = {
        var vcs: [OrderViewController] = []
        for i in [4,7,6,5] {
            let orderVC = OrderViewController()
            orderVC.status = i
            vcs.append(orderVC)
        }
        return vcs
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
    }
    
    private func configView() {
        let topImageView = UIImageView(image: UIImage(named: "home_top_bg"))
        self.view.addSubview(topImageView)
        topImageView.contentMode = .scaleAspectFill
        self.view.backgroundColor = UIColor.hex(with: "F7F7F7")
        topImageView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
        }
        let topTitleView = UIImageView(image: UIImage(named: "order_top_title"))
        self.view.addSubview(topTitleView)
        topTitleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(29)
            make.top.equalToSuperview().offset(88)
        }
        let topAlertView = UIImageView(image: UIImage(named: "order_top_alert"))
        self.view.addSubview(topAlertView)
        topAlertView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(44)
        }
        let containerView = UIView()
        self.view.addSubview(containerView)
        containerView.backgroundColor = UIColor.hex(with: "#f7f7f7")
        containerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(182)
        }
        containerView.layer.masksToBounds = true
        containerView.layer.cornerRadius = 20
        containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        let titleView = UIStackView()
        containerView.addSubview(titleView)
        titleView.axis = .horizontal
        titleView.distribution = .fillEqually
        titleView.alignment = .fill
        titleView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(30)
            make.top.equalToSuperview().offset(15)
        }
        self.titles
            .subscribe(onNext: { titles in
                let subViews = titleView.subviews
                subViews.forEach({$0.removeFromSuperview()})
                let views = titles.map { model in
                    let view = UIView()
                    let button = UIButton(type: .custom)
                    button.setAttributedTitle(NSAttributedString(string: model.title, attributes: [.foregroundColor: UIColor.hex(with: "666666"), .font: UIFont.systemFont(ofSize: 14)]), for: .normal)
                    button.setAttributedTitle(NSAttributedString(string: model.title, attributes: [.foregroundColor: UIColor.hex(with: "121011"), .font: UIFont.systemFont(ofSize: 14, weight: .medium)]), for: .selected)
                    button.isSelected = model.selected
                    view.addSubview(button)
                    button.snp.makeConstraints { make in
                        make.top.centerX.equalToSuperview()
                    }
                    button.rx.tap
                        .subscribe(onNext: { [weak self] event in
                            let newTitles = [OrderStateModel(title: "All".locale, id: 4, selected: model.id == 4),OrderStateModel(title: "Apply".locale, id: 7, selected: model.id == 7),OrderStateModel(title: "Repayment".locale, id: 6, selected: model.id == 6),OrderStateModel(title: "Finished".locale, id: 5, selected: model.id == 5)]
                            self?.titles.accept(newTitles)
                        })
                        .disposed(by: self.bag)
                    let sliderView = UIView()
                    view.addSubview(sliderView)
                    sliderView.backgroundColor = model.selected ? UIColor.hex(with: "126BFB") : UIColor.hex(with: "#F7F7F7")
                    sliderView.snp.makeConstraints { make in
                        make.bottom.equalToSuperview()
                        make.left.right.equalTo(button)
                        make.height.equalTo(3)
                    }
                    return view
                }
                views.forEach { view in
                    titleView.addArrangedSubview(view)
                }
            })
            .disposed(by: self.bag)
        let source = [OrderStateModel(title: "All".locale, id: 4, selected: 4 == self.status),OrderStateModel(title: "Apply".locale, id: 7, selected: 7 == self.status),OrderStateModel(title: "Repayment".locale, id: 6, selected: 6 == self.status),OrderStateModel(title: "Finished".locale, id: 5, selected: 5 == self.status)]
        self.titles.accept(source)
        self.titles
            .map { titles in
                let title = titles.filter({$0.selected}).first
                return titles.firstIndex(where: {$0.id == title?.id})
            }
            .compactMap({$0})
            .bind(to: self.currentIndex)
            .disposed(by: self.bag)
        let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal)
        self.addChild(pageViewController)
        let idx = source.firstIndex(where: {$0.id == self.status}) ?? 0
        pageViewController.setViewControllers([self.childs[idx]], direction: .forward, animated: false)
        pageViewController.delegate = self
        pageViewController.dataSource = self
        self.view.addSubview(pageViewController.view)
        pageViewController.view.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom)
        }
        for view in pageViewController.view.subviews {
                    if let scrollView = view as? UIScrollView {
                        scrollView.isScrollEnabled = false
                    }
                }
        self.currentIndex
            .subscribe(onNext: { [weak self] index in
                if let currentViewController = pageViewController.viewControllers?.first, let currentIndex = self!.childs.firstIndex(of: currentViewController) {
                    let target = self!.childs[index]
                    if (index > currentIndex) {
                        pageViewController.setViewControllers([target], direction: .forward, animated: true)
                    } else {
                        pageViewController.setViewControllers([target], direction: .reverse, animated: true)
                    }
                } else {
                    let vc = self!.childs[index]
                    pageViewController.setViewControllers([vc], direction: .forward, animated: false)
                }
            })
            .disposed(by: self.bag)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension OrdersViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let index = self.childs.firstIndex(of: viewController), index < self.childs.count - 1 else {
                    return nil
                }
        return self.childs[index + 1]
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let index = self.childs.firstIndex(of: viewController), index > 0 else {
                    return nil
                }
        return self.childs[index - 1]
    }
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        
    }
}
